package org.soderiakelvy.model.dao.imp;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.soderiakelvy.model.dao.RepartoDao;
import org.soderiakelvy.model.domain.RepartoVO;
import org.soderiakelvy.model.util.HibernateUtil;

public class RepartoDaoImp implements RepartoDao, Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void insertRepartoVO(RepartoVO reparto) throws Exception {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.save(reparto);
		session.getTransaction().commit();
		session.close();
	}

	@Override
	public void updateRepartoVO(RepartoVO reparto) throws Exception {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.update(reparto);
		session.getTransaction().commit();
		session.close();
	}

	@Override
	public void deleteRepartoVO(RepartoVO reparto) throws Exception {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.delete(reparto);
		session.getTransaction().commit();
		session.close();
	}

	@Override
	public List<RepartoVO> getRepartos() throws Exception {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(RepartoVO.class);
		List<RepartoVO> repartos = criteria.list();
		session.close();
		return repartos;
	}

	@Override
	public RepartoVO getRepartoById(long repartoId) throws Exception {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(RepartoVO.class);
		criteria.add(Restrictions.eq("repartoId", repartoId));
		RepartoVO reparto = (RepartoVO)criteria.uniqueResult();
		session.close();
		return reparto;
	}

	@Override
	public RepartoVO getRepartoByNombre(String nombre) {
		try {
			SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
			Session session = sessionFactory.openSession();
			Criteria criteria = session.createCriteria(RepartoVO.class);
			criteria.add(Restrictions.eq("nombre", nombre));
			RepartoVO reparto = (RepartoVO)criteria.uniqueResult();
			session.close();
			return reparto;
		} catch (Exception e) {
			return new RepartoVO();
		}
		
	}

}
